/**
 * This file is Copyright © 2008 Software Craftsmen Limited. All Rights Reserved.
 */
package com.softwarecraftsmen.archivers.tar.fileEntries.headers;

import org.jetbrains.annotations.NotNull;
import com.softwarecraftsmen.archivers.tar.BlockWriter;

public class FileHeaderFieldWriter
{
	private static final String Posix1003_1_1988Magic = "ustar";
	private static final String GnuMagic = "ustar  ";

	private final ByteWriter writer;

	public FileHeaderFieldWriter(final @NotNull ByteWriter byteWriter)
	{
		writer = byteWriter;
	}

	public void writeFileName(final @NotNull String fileName)
	{
		writer.writeFileName(fileName);
	}

	public void writeMode(final long mode)
	{
		writer.writeAsNullTerminatedOctalAsciiString(mode, 100, 8);
	}

	public void writeUserId(final long userId)
	{
		writer.writeAsNullTerminatedOctalAsciiString(userId, 108, 8);
	}

	public void writeGroupId(final long groupId)
	{
		writer.writeAsNullTerminatedOctalAsciiString(groupId, 116, 8);
	}

	public void writeFileSize(final long fileSize)
	{
		writer.writeAsNullTerminatedOctalAsciiString(fileSize, 124, 12);
	}

	public void writeFileModificationTime(final long fileModificationTime)
	{
		writer.writeAsNullTerminatedOctalAsciiString(fileModificationTime, 136, 12);
	}

	public void writeLinkFlag(final @NotNull LinkFlag linkFlag)
	{
		writer.writeLinkFlag(linkFlag);
	}

	public void writeLinkName(final @NotNull String linkName)
	{
		writer.writeNameField(linkName, 157, 100);
	}

	public void writeMagic()
	{
		writer.writeNameField(GnuMagic, 257, 8);
	}

	public void writeUserName(final @NotNull String userName) {writer.writeNameField(userName, 265, 32);}

	public void writerGroupName(final @NotNull String groupName) {writer.writeNameField(groupName, 297, 32);}

	public void writeMajorDeviceId(final long majorDeviceId) {writer.writeAsNullTerminatedOctalAsciiString(majorDeviceId, 329, 8);}

	public void writeMinorDeviceId(final long minorDeviceId) {writer.writeAsNullTerminatedOctalAsciiString(minorDeviceId, 337, 8);}

	public void writeCheckSum()
	{
		long checkSum = 0;
		for (int index = 0; index < BlockWriter.BlockSize; ++index)
		{
			checkSum += 0xFF & writer.byteAt(index);
		}
		writer.writeCheckSumOctalBytes(checkSum, 148, 8);
	}

	public void pad()
	{
		writer.pad(345);
	}
}
